﻿using System;
using System.Windows.Browser;
using System.Collections.Generic;

namespace SilverQuery
{
	/// <summary>
	/// Centralized repository of event callbacks.
	/// </summary>
	internal static class EventCallbackRegistry
	{
		private static Dictionary<string, RegistryEntry> _registry = new Dictionary<string,RegistryEntry>();
		private static Dictionary<EventCallback, string> _callbackIndex = new Dictionary<EventCallback,string>();
	
		internal static void Add(string callbackId, EventCallback callback, ScriptObject fn)
		{
			_registry[callbackId] = new RegistryEntry() { Callback = callback, ScriptFunction = fn };
			_callbackIndex[callback] = callbackId;
		}

		private class RegistryEntry
		{
			public EventCallback Callback;
			public ScriptObject ScriptFunction;
		}

		internal static EventCallback Get(string callbackId)
		{
			RegistryEntry entry;
			if (_registry.TryGetValue(callbackId, out entry))
				return entry.Callback;
			return null;
		}

		/// <summary>
		/// Get the script function that has already been registered for the specified EventCallback.
		/// </summary>
		/// <param name="callback"></param>
		/// <returns></returns>
		internal static ScriptObject GetScriptFunction(EventCallback callback)
		{
			string id;
			if (_callbackIndex.TryGetValue(callback, out id))
			{
				RegistryEntry entry;
				if (_registry.TryGetValue(id, out entry))
					return entry.ScriptFunction;
			}
			return null;
		}
	}
}
